<template>
  <div class="xtx-checkbox" @click="changeChecked">
    <!-- 复选框切换选择显示 -->
    <i class="iconfont icon-checked" v-if="checked"></i>
    <i class="iconfont icon-unchecked" v-else></i>
    <!-- 内容 -->
    <span v-if="slots.default">
      <slot></slot>
    </span>
  </div>
</template>
<script lang="ts">
import { ref, watch } from 'vue';

export default {
  name: 'XtxCheckbox',
  props: {
    // 父组件控制复选框数据
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  setup(props, content) {
    // 控制复选框
    const checked = ref(false)
    const changeChecked = () => {
      checked.value = !checked.value
      // 使用emit通知父组件数据的改变
      content.emit('update:modelValue', checked.value)
      // 触发change
      content.emit('change', checked.value)
    }
    // 使用侦听器，得到父组件传递数据，给checked数据
    watch(() => props.modelValue, () => {
      checked.value = props.modelValue
    })
    // 拿到插槽内容，如果有内容创建span节点，否则就不创建
    const slots = content.slots
    return {
      checked,
      changeChecked,
      slots,
    }
  }
}
</script>
<style lang="less" scoped>
@import '../../assets/styles/mixins.less';
@import '../../assets/styles/variables.less';

.xtx-checkbox {
  display: inline-block;
  margin-right: 2px;

  .icon-checked {
    color: @xtxColor;

    ~span {
      color: @xtxColor;
    }
  }

  i {
    position: relative;
    top: 1px;
  }

  span {
    margin-left: 2px;
  }
}
</style>